var HSRroduct = function () {

    this.$grid_selector = $("#jira_sync_hs_product_grid_table");
    this.pager_selector = "#jira_sync_hs_product_grid_pager";

    // 最后搜索内容
    this.lastSearch = '';

    // 请求url
    this.URL = {
        EDIT: '/jira/hs/product/{{id}}',
        PRODUCT_SYNC: '/jira/hs/product/sync',
        PROJECT_LIST: '/jira/project/page'
    };

    var self = this;
    this.colModel = [
        { name: 'productId', hidden: true, key: true },
        { name: 'projectId', hidden: true },
        { name: 'productName', width: 30 },
        { name: 'projectName', width: 30 },
        {
            width: 100, fixed: true, sortable: false, formatter: function (cellValue, row) {
                return self.operatingTemplate({ rowId: row.rowId });
            }
        }
    ];

    this.operatingTemplate = _.template(
        '<div class="btn-group">' +
        '<button id="jira_sync_product_{{rowId}}" class="btn btn-sm btn-primary jira-sync-product">编辑</button>' +
        '</div>'
    );


    this.options = {
        moduleKey: 'jira/hs/product',
        pager: this.pager_selector,
        sortname: 'productId',
        caption: "恒生产品管理",
        colNames: ['产品ID', '项目ID', '产品名称', 'jira项目名称', '操作'],
        colModel: this.colModel,
        navbarDefaultIcon: {
            add: false,
            edit: false,
            view: false,
            del: false
        }
    };

    this.template = _.template('<form id="form_hs_product_edit" style="padding: 16px;" class="form-horizontal" method="PUT">\
                                <input type="hidden" name="projectName">\
                                <input type="hidden" name="productId" value="{{productId}}">\
                                <div class="form-group">\
                                    <label class="col-xs-2 control-label">产品名称</label>\
                                    <div class="col-xs-10"><input readonly class="form-control" type="text" name="productName" value="{{productName}}"></div>\
                                </div>\
                                <div class="form-group">\
                                    <label class="col-xs-2 control-label">jira项目名称</label>\
                                    <div class="col-xs-10">\
                                        <select class="form-control" name="projectId" ></select>\
                                    </div>\
                                </div>\
                             </form>');

};

HSRroduct.prototype = {
    // 初始化表格
    initGird: function () {

        var self = this;
        this.$grid_selector
            .xumf_jqGird(this.options)
            .xumf_jqGird('navGrid', this.pager_selector)
            .jqGrid('navButtonAdd', this.pager_selector,
                {
                    caption: '',
                    title: "同步恒生产品数据",
                    buttonicon: "fa fa-cloud-download",
                    onClickButton: function () {
                        self.syncProductAction();
                    },
                    position: "first"
                })
            .jqGrid('navButtonAdd', this.pager_selector,
                {
                    caption: '',
                    title: "搜索",
                    buttonicon: "fa fa-search orange",
                    onClickButton: function () {
                        self.searchUI();
                    },
                    position: "first"
                });
        // 绑定删除事件
        this.$grid_selector.delegate('.jira-sync-product', 'click', function (event) {
            var rowId = $(event.currentTarget).attr('id').split('_')[3];
            var row = self.$grid_selector.jqGrid('getRowData', rowId);
            self.editUI(row);
        });
    },
    searchUI: function () {
        var self = this;
        layer.open({
            maxmin: false,
            title: '搜索',
            area: ['500px', 300],
            btn: ['搜索', '取消'],
            content: _.template('<form style="padding:12px;" class="form-horizontal">\
                        <div class="form-group">\
                            <label class="col-xs-5 control-label" for="keyword">恒生产品名称/jira项目名称：</label>\
                            <div class="col-xs-7">\
                                <input name="keyword" class="form-control" value="{{keyword}}" autocomplete="off" type="text">\
                            </div>\
                        </div>\
                    </form>')({ keyword: this.lastSearch }),
            yes: function (index, layero) {
                var $form = $(layero).find('form');
                self.lastSearch = $form.find('input[name=keyword]').val();
                self.$grid_selector.setGridParam({
                    datatype: "json",
                    postData: { searchString: self.lastSearch }
                }).trigger('reloadGrid').setGridParam({
                    datatype: "json",
                    postData: { searchString: '' }
                });
                layer.close(index);
            }
        })
    },
    /**
     * 同步产品操作
     */
    syncProductAction: function () {

        var self = this;
        $.xumf.ajaxAndLoading({
            type: 'post',
            url: this.URL.PRODUCT_SYNC
        }).success(function (res) {
            res.success && self.$grid_selector.trigger("reloadGrid");
            $.xumf.gritter(res);
        });
    },
    /**
     * 编辑操作
     */
    editUI: function (rowData) {
        var self = this;

        var defaultValues = $.extend({
            productId: '',
            productName: '',
            projectId: '',
            projectName: ''
        }, rowData);
        var success = function (layero, index) {
            var $form = $(layero).find('form');
            // 设置默认值
            if ('' !== defaultValues.projectId) {
                $form.find('select[name=projectId]').append(
                    _.template('<option value="{{projectId}}">{{projectName}}</option>')(defaultValues)
                )
            }

            $form.find('select[name=projectId]').select2({
                placeholder: "请选择",
                allowClear: true,
                ajax: {
                    url: self.URL.PROJECT_LIST,
                    data: function (params) {
                        return {
                            searchString: params.term,
                            page: params.page || 1,
                            rows: 10
                        };
                    },
                    processResults: function (res, params) {
                        params.page = params.page || 1;
                        var rows = _.map(res.rows, function (o) {
                            return {
                                id: o.value,
                                text: o.label
                            }
                        });
                        return {
                            results: rows,
                            pagination: {
                                more: res.page < res.total
                            }
                        };
                    }
                }
            });
        };

        // 显示弹框
        layer.open({
            title: '编辑字典',
            area: ["650px", "200px"],
            content: this.template(rowData),
            btn: ['确定', '取消'],
            success: success,
            yes: function (index, layero) {
                var $form = $(layero).find('form');
                layer.close(index);
                self.editAction($form);
            }
        });
    },
    /**
     * 编辑操作
     * @returns {boolean} 是否阻止dialog消失，true为消失，false则相反
     */
    editAction: function ($form) {
        var self = this;
        var productId = $form.find('input[name=productId]').val();
        $form.attr('action', _.template(this.URL.EDIT)({ id: productId }));
        var text = $form.find("select[name=projectId] option:selected").text();
        $form.find('input[name=projectName]').val(text);
        $.xumf.showLoading();
        $form.ajaxSubmit({
            type: 'PUT',
            success: function (res) {
                $.xumf.hideLoading();
                $.xumf.gritter(res);
                res.success && self.$grid_selector.trigger("reloadGrid")
            }
        });
    }
};

